package com.shop.controller.users;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.shop.entity.users.User;
import com.shop.service.user.User_service;
import com.shop.util.EmailVerifyUtil;

@Controller
public class UserLogin {

	@Autowired
	private User_service userService;

	/**
	 * 用户登陆
	 * 
	 * @param request
	 * @return
	 * @throws IOException
	 */
	@ResponseBody
	@RequestMapping("/UserLoginVerify")
	public String UserLoginVerify(HttpServletRequest request) throws IOException {
		String userName = request.getParameter("username");
		String passWord = request.getParameter("password");
		String code = request.getParameter("verifyCode");
		String validateCode = (String) request.getSession().getAttribute("validateCode");

		if (!code.equals(validateCode)) {//验证 验证码
			return "3";
		}

		if (!new EmailVerifyUtil().stringVerify(userName)) {//账号登陆
			User qn = userService.qreayUserByName(userName);
			if (qn == null) {
				return "2";
			}
			if (qn.getPassword().equals(passWord)) {
				// response.getWriter().println("<font
				// color='green'>登陆成功</font>");
				request.getSession().setAttribute("user", qn);
				return "0";
			} else {
				// response.getWriter().println("<font
				// color='red'>密码错误</font>");
				return "1";
			}

		}

		User em = userService.qreayUserByEmail(userName);//邮箱登陆
		if (em == null) {
			return "2";
		}
		if (em.getPassword().equals(passWord)) {
			// response.getWriter().println("<font color='green'>登陆成功</font>");
			request.getSession().setAttribute("user", em);
			return "0";
		} else {
			// response.getWriter().println("<font color='red'>密码错误</font>");
			return "1";
		}

	}
}
